<template>
    <div>
        <el-form :model="updateRole" ref="roleFormRef" label-width="100px" label-position="right" style="width: 400px;"
            :rules="rules">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="updateRole.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-tree style="max-width:600px" :data="authList" show-checkbox node-key="index" :default-expand-all="true" :default-checked-keys="checkedKeys" @check-change="handleCheckChange" >

            </el-tree>
        </el-form>
    </div>
</template>
<script setup lang="ts">
import { reactive,onMounted,ref } from 'vue';
import type { roleInforDate } from '@/api/role/type';
import type { FormRules } from 'element-plus';
import menuList from '@/config/menuConfig';
// 接受父组件传递过来的要编辑的角色对象
const props = defineProps(["role"]);
let updateRole = ref<roleInforDate>({
    name: ""
});
// 表单校验规则
const rules = reactive<FormRules>({
    name:[{ required:true,message:"请输入角色名称",trigger:"blur"}],
});
//树形控件数据数组
const authList = ref([])
// 树形控件中所有选中项数组
const checkedKeys = ref<string[]>([])
//处理树形控件元素对象
const getAuthNodes =(menuList:any)=>{
    return menuList.map((item:any)=>{
        if(!item.children){
            return{index: item.index,
                label:item.title
            }
        }else{
            return{
                index:item.index,
                label:item.title,
                children:getAuthNodes(item.children)
            }
        }
    })
}
interface Tree {
    index:string
}
//树形控件选择回调
const handleCheckChange =(
    data: Tree,
    checked: boolean,
    _indeterminate: boolean
)=>{
    // 如果选中就添加到选中项数组中
    if(checked){
        if(checkedKeys.value.indexOf(data.index)==-1){
            checkedKeys.value.push(data.index)
        }else{
            if(checkedKeys.value.indexOf(data.index)!=-1){
                // 如果取消勾选时就从选中的数组中删除
                checkedKeys.value.splice(checkedKeys.value.indexOf(data.index),1)
            }
        }
    }
};
// 为夫组件提供数据方法
const getMenus =()=>{
    updateRole.value.menus = checkedKeys.value;
    return updateRole.value
}
// 对外暴露
defineExpose({
    getMenus
})
onMounted(()=>{
    updateRole.value = { ...props.role };
    authList.value = getAuthNodes(menuList)
    checkedKeys.value =[...props .role.menus]
})
</script>

<style scoped></style>